package org.anupta.game.utils.sql;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.dbcp.BasicDataSource;

public class Database {
    private static Map<String, Database> databases = new HashMap<String, Database>();
    private final BasicDataSource source = new BasicDataSource();

    private Database(String driver, String url, String user, String password) {
        source.setDriverClassName(driver);
        source.setUrl(url);
        source.setUsername(user);
        source.setPassword(password);
        source.setPoolPreparedStatements(true);
    }

    public BasicDataSource getSource(){
        return source;
    }

    public static Database getDatabase(String driver, String url, String user, String password) {
        if (!databases.containsKey(url)) {
            Database db = new Database(driver, url, user, password);
            databases.put(url, db);
            return db;
        }
        return databases.get(url);
    }

    public static Database getDatabase(String url) {
        return databases.get(url);
    }
    
    public Connection getConnection(){
    	Connection connect = null;
    	try {
			connect = source.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connect;
    }

    public static void closeAll(){
        for(Database database : databases.values()){
            database.close();
        }
    }

    public void close(){
        try {
            source.close();
            databases.remove(this);
        } catch (SQLException ex) {
            Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
